package nc.ui.so.m30.billui.action;

import java.awt.event.ActionEvent;

import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.UIDialog;
import nc.ui.pub.bill.BillCardPanel;
import nc.ui.pubapp.uif2app.model.BillManageModel;
import nc.ui.so.m30.billui.view.SaleOrderBillForm;
import nc.ui.so.pub.keyvalue.CardKeyValue;
import nc.ui.uif2.NCAction;
import nc.ui.uif2.ShowStatusBarMsgUtil;
import nc.vo.pub.lang.UFDate;
import nc.vo.so.pub.keyvalue.IKeyValue;

public abstract class AbstractPriceSoAction extends  NCAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public BillManageModel model;
	public SaleOrderBillForm editor;

	@Override
	public void doAction(ActionEvent event) throws Exception {
		ShowStatusBarMsgUtil.showStatusBarMsg("Working...", getModel().getContext());
		if(check()) {
			if(doExec()) {
				ShowStatusBarMsgUtil.showStatusBarMsg("Done", getModel().getContext());
				return;
			}
		}
		ShowStatusBarMsgUtil.showStatusBarMsg("Break", getModel().getContext());
	}
	
	protected abstract boolean doExec() throws Exception;

	private boolean check() {
		StringBuffer hint = new StringBuffer();
		
		BillCardPanel card = editor.getBillCardPanel();
		IKeyValue keyValue = new CardKeyValue(card);
		UFDate dbilldate = (UFDate) keyValue.getHeadValue("dbilldate");
		if(dbilldate == null) {
			hint.append("BillDate can not be blank");
			MessageDialog.showErrorDlg(editor, "hint", hint.toString());
			return false;
		}
		hint = new StringBuffer();
		
		String corigcurrencyid = (String) keyValue.getHeadValue("corigcurrencyid");
		if(corigcurrencyid == null) {
			hint.append("Currency can not be blank");
			MessageDialog.showErrorDlg(editor, "hint", hint.toString());
			return false;
		}
		hint = new StringBuffer();
		
		int[] rows = card.getBillTable().getSelectedRows();
		if(rows == null || rows.length == 0) {
			hint.append("Select the table body row");
			MessageDialog.showErrorDlg(editor, "hint", hint.toString());
			return false;
		}
		hint = new StringBuffer();
		hint.append("The following table body rows have been selected:\n");
		for(int row : rows) {
			hint.append("["+(row+1)+"]");
		}
		hint.append("\nConfirm?");
		
		if(UIDialog.ID_OK == MessageDialog.showOkCancelDlg(editor, "question", hint.toString())) {
			return true;
		}
		
		return false;
	}

	public BillManageModel getModel() {
		return model;
	}

	public void setModel(BillManageModel model) {
		this.model = model;
		this.model.addAppEventListener(this);
	}

	public SaleOrderBillForm getEditor() {
		return editor;
	}

	public void setEditor(SaleOrderBillForm editor) {
		this.editor = editor;
	}
}
